package projectisd.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;

public class AfmeldenGUI {
	/* Constants. */
	private static final String LISTING_ROOT_PANEL = "guiListing";
	private static final String FORM_ROOT_PANEL = "guiForm";
	private static final String STATUS_ROOT_PANEL = "guiStatus";
	private static final String TOOL_BAR_ROOT_PANEL = "guiToolBar";
	private static final int EDIT_LINK = 5;
	private static final int REMOVE_LINK = 6;

	/* GUI Widgets */
	protected Button addButton;
	protected Button updateButton;
	protected Button addNewButton;
	protected Button okButton;
	protected ListBox lesUurNrField;
	protected TextArea redenField;
	protected TextBox studentNummerField;
	protected Label titel = new Label("Afmelden");
	protected Label leeg = new Label("");
	protected Label status;
	protected Grid listGrid;
	protected Grid formGrid;
	protected Grid formGrid2;
	protected Image hulogo = new Image("http://jansen-schoonhoven.com/Downloads/hulogo.jpg");

	private Label datePickerLabel;
	private DatePicker myDatePicker;
	private String dateString;
	private int i;

	/* Data model */
	private List<Les> lessen;
	private ArrayList<Les> selectieLessen;

	private List<Afmelden> afmeldingen;
	private Afmelden currentAfmelden;
	protected AfmeldenDelegate afmeldenService;

	public void init() {
		addButton = new Button("Add afmelding");
		addNewButton = new Button("Add new afmelding");
		updateButton = new Button("Update afmelding");
		lesUurNrField = new ListBox();
		redenField = new TextArea();
		redenField.setVisibleLines(6);
		studentNummerField = new TextBox();
		status = new Label();
		listGrid = new Grid(2,12);

		//Datum widget
		datePickerLabel = new Label();
		myDatePicker = new DatePicker();
		myDatePicker.addValueChangeHandler(new ValueChangeHandler() {
			public void onValueChange(ValueChangeEvent event) {
				Date date = (Date) event.getValue();
				dateString = DateTimeFormat.getMediumDateFormat().format(date);
				datePickerLabel.setText(dateString);
			}
		});

		okButton = new Button("Volgende");
		okButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (studentNummerField.getText().length() == 0)
				{	Window.alert("Studentnummer moet gevuld worden");
				} else if (!studentNummerField.getText().matches("^(0)$|^([1-9][0-9]*)$"))
				{ Window.alert ("Studentnummer bevat letters of tekens");
				} else if (!studentNummerField.getText().matches("^(0)$|^([1-9][0-9]*)$"))
				{ Window.alert ("Studentnummer bevat letters of tekens");
				} else if (datePickerLabel.getText().length() == 0)
				{	Window.alert("Datum moet geselecteerd worden");
				} else {
					loadForm2(currentAfmelden);
				}
			}
		});
		i = 1;
		formGrid = new Grid(6,3);
		buildForm();
		placeWidgets();
	}

	private void buildForm() {

		if(i == 0) {
			formGrid.setWidget(0, 0, titel);
			formGrid.setWidget(0, 2, hulogo);

			formGrid.setWidget(1, 0, new Label("Les begint om"));
			formGrid.setWidget(1, 1, lesUurNrField); 

			formGrid.setWidget(2, 0, new Label("Reden"));
			formGrid.setWidget(2, 1, redenField); 

			formGrid.setWidget(3, 0, updateButton);
			formGrid.setWidget(3, 1, addButton);
		}
		else {
			formGrid.setVisible(false);

			formGrid.setWidget(0, 0, titel);
			formGrid.setWidget(0, 2, hulogo);

			formGrid.setWidget(1, 0, new Label("Studentnummer"));
			formGrid.setWidget(1, 1, studentNummerField); 

			formGrid.setWidget(2, 0, new Label("Datum"));
			formGrid.setWidget(2, 1, myDatePicker); 

			formGrid.setWidget(3, 0, leeg);
			formGrid.setWidget(3, 1, okButton);
		}
	}

	private void placeWidgets() {
		RootPanel.get(LISTING_ROOT_PANEL).add(listGrid);
		RootPanel.get(FORM_ROOT_PANEL).add(formGrid);
		RootPanel.get(STATUS_ROOT_PANEL).add(status);
		RootPanel.get(TOOL_BAR_ROOT_PANEL).add(addNewButton);
	}

	public void hideGui() {
		formGrid.setVisible(false);
		listGrid.setVisible(false);
		status.setVisible(false);
		addNewButton.setVisible(false);
	}


	private void loadForm(Afmelden afmelden) {
		buildForm();
		this.formGrid.setVisible(true);
		currentAfmelden = afmelden;
		this.studentNummerField.setText(afmelden.getStudentnummer());
	}

	private void loadForm2(Afmelden afmelden) {
		currentAfmelden = afmelden;
		i = 0;
		buildForm();
		this.formGrid.setVisible(true);
		this.lesUurNrField.clear();
		this.selectieLessen = new ArrayList<Les>();
		if(selectieLessen != null){
			selectieLessen.clear();
		}
		int index = 0;
		int selected = 0;
		for (Les les : lessen) {
			if(datePickerLabel.getText().equalsIgnoreCase(les.getDatum())){
				this.lesUurNrField.addItem(les.getBegintijd());
				selectieLessen.add(les);

				if (les.getLesUurNr().longValue() == 
					afmelden.getLesUurNr().longValue()) {
					selected = index;
				}
				index++; 
			} 
		} 
		if (selectieLessen.size() != 0){
			this.formGrid.setVisible(true);
			this.lesUurNrField.setSelectedIndex(selected);
			this.redenField.setText(afmelden.getReden());
			int i = 1;	
		}	else {
			i = 1;
			buildForm();
			this.formGrid.setVisible(true);
			Window.alert("Geen lessen op deze datum.");
		}
	}


	private void copyFieldDateToAfmelden() {

		int selected = this.lesUurNrField.getSelectedIndex();

		Long lesUurNr = 0L;

		currentAfmelden.setLesUurNr(selectieLessen.get(selected).getLesUurNr());
		currentAfmelden.setStudentnummer(studentNummerField.getText());
		currentAfmelden.setReden(redenField.getText());
	}

	public void gui_eventListGridClicked(Cell cellClicked) {
		int row = cellClicked.getRowIndex();
		int col = cellClicked.getCellIndex();

		Afmelden afmelden = this.afmeldingen.get(row);

		if (col==EDIT_LINK) {
			i = 1;
			this.addNewButton.setVisible(false);
			this.updateButton.setVisible(true);
			this.addButton.setVisible(false);
			loadForm(afmelden);
		} else if (col==REMOVE_LINK) {
			if (Window.confirm("Verwijderen afmelding?")) {
				this.afmeldenService.removeAfmelden(afmelden);
				formGrid.setVisible(false);
			}
		}
	}


	public void gui_eventAddButtonClicked() {
		if	(redenField.getText().length() == 0)
		{	Window.alert("Reden moet gevuld worden");
		} 	else { 
			addNewButton.setVisible(true);
			formGrid.setVisible(false);
			copyFieldDateToAfmelden();
			this.afmeldenService.addAfmelden(currentAfmelden);
			i = 1;
		}
	}

	public void gui_eventUpdateButtonClicked() {
		if	(redenField.getText().length() == 0)
		{	Window.alert("Reden moet gevuld worden");

		}	else {
			addNewButton.setVisible(true);
			formGrid.setVisible(false);
			copyFieldDateToAfmelden();
			this.afmeldenService.updateAfmelden(currentAfmelden);
		}
	}

	public void gui_eventAddNewButtonClicked() {
		this.addNewButton.setVisible(false);
		this.updateButton.setVisible(false);
		this.addButton.setVisible(true);
		Afmelden afmelden = new Afmelden();
		afmelden.setLesUurNr(0L);
		i = 1;
		loadForm(afmelden);
	}

	public void service_lessenListRetrievedFromService(List<Les> result) {
		this.lessen = result;	
	}

	public void service_eventListRetrievedFromService(List<Afmelden> result) {
		status.setText("Retrieved afmeldingen list");
		status.setVisible(true);

		//formGrid.setVisible(false);
		listGrid.setVisible(true);
		status.setVisible(true);
		addNewButton.setVisible(true);

		this.afmeldingen = result;
		this.listGrid.clear();
		this.listGrid.resizeRows(this.afmeldingen.size());
		int row = 0;
		this.addNewButton.setVisible(true);

		for (Afmelden afmelden : result) {
			if (lessen != null)
				for (Les les : lessen) {
					if (les.getLesUurNr().longValue() == 
						afmelden.getLesUurNr().longValue()) {
						this.listGrid.setWidget(row, 0, new Label (les.getDatum()));
						this.listGrid.setWidget(row, 1, new Label (les.getBegintijd()));
						this.listGrid.setWidget(row, 2, new Label (les.getEindtijd()));
						this.listGrid.setWidget(row, 3, new Label (afmelden.getStudentnummer()));
						this.listGrid.setWidget(row, 4, new Label (afmelden.getReden()));
						this.listGrid.setWidget(row, EDIT_LINK, new Hyperlink("Edit", null));
						this.listGrid.setWidget(row, REMOVE_LINK, new Hyperlink("Remove", null));
						row ++;
					}
				}
		}
	}

	public void service_eventAddAfmeldenSuccessful() {
		status.setText("Afmelding was successfully added");
		this.afmeldenService.listAfmeldingen();
	}

	public void service_eventUpdateSuccessful() {
		status.setText("Afmelding was successfully updated");
		this.afmeldenService.listAfmeldingen();
	}
	public void service_eventRemoveAfmeldenSuccessful() {
		status.setText("Afmelding was removed");
		this.afmeldenService.listAfmeldingen();
	}

	public void service_eventUpdateAfmeldenFailed(Throwable caught) {
		status.setText("Update afmelding failed");
	}

	public void service_eventAddAfmeldenFailed(Throwable caught) {
		status.setText("Unable to update afmelding");
	}

	public void service_eventRemoveAfmeldenFailed(Throwable caught) {
		status.setText("Remove afmelding failed");
	}

	public void service_eventListAfmeldingenFailed(Throwable caught) {
		status.setText("Unable to get afmelding list");

	}

}
